﻿#include "delayoperation.h"
#include <QCoreApplication>

DelayOperation::DelayOperation(QObject *parent)
    : Operation{parent}
    , m_nDuration(0)
{

}

Operation* DelayOperation::clone(Operation* pOperation){
    Operation::clone(pOperation);

    m_nDuration = ((DelayOperation*)pOperation)->GetDuration();
    return this;
}

void DelayOperation::run()
{
    emit sendMessage("Start delay...");
    QTime dieTime = QTime::currentTime().addMSecs(m_nDuration);
    while (QTime::currentTime() < dieTime)
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
    emit sendMessage("Finish delay!");
}

int DelayOperation::nDuration() const
{
    return m_nDuration;
}

void DelayOperation::setNDuration(int newNDuration)
{
    m_nDuration = newNDuration;
}

QString DelayOperation::getClassName()
{
    return this->metaObject()->className();
}

void DelayOperation::writeXML(QXmlStreamWriter &writer)
{
    // 写入当前操作的信息
    writer.writeStartElement("DelayOperation");
    writer.writeAttribute("device", m_strDeviceID);
    writer.writeTextElement("duration", QString::number(m_nDuration));
    writer.writeEndElement(); // 结束当前操作的元素
}

void DelayOperation::readFromXML(QXmlStreamReader &reader)
{
    QXmlStreamAttributes attributes = reader.attributes();
    if (attributes.hasAttribute("device")) {
        m_strDeviceID = attributes.value("device").toString();
    }

    QXmlStreamReader::TokenType token = reader.readNext();
    while (!(reader.tokenType() == QXmlStreamReader::EndElement
             && reader.name() == QStringLiteral("DelayOperation"))) {
        if (reader.name() == QStringLiteral("duration")) {
            m_nDuration = reader.readElementText().toInt();
        }

        reader.readNext();
    }
}
